package com.school.controller;

import com.school.entity.ClassEntity;
import com.school.service.ClassService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@RestController
@RequestMapping("/api/class")
public class ClassController {
    @Autowired
    private ClassService classService;

    @GetMapping("/list")
    public List<ClassEntity> list() {
        return classService.findAll();
    }

    @PostMapping("/add")
    public Map<String, Object> add(@RequestBody ClassEntity classEntity) {
        Map<String, Object> result = new HashMap<>();
        if (classService.findByName(classEntity.getName()).isPresent()) {
            result.put("success", false);
            result.put("message", "班级名已存在");
            return result;
        }
        classService.save(classEntity);
        result.put("success", true);
        return result;
    }

    @PostMapping("/edit")
    public Map<String, Object> edit(@RequestBody ClassEntity classEntity) {
        Map<String, Object> result = new HashMap<>();
        Optional<ClassEntity> exist = classService.findById(classEntity.getId());
        if (exist.isEmpty()) {
            result.put("success", false);
            result.put("message", "班级不存在");
            return result;
        }
        // 检查重名
        Optional<ClassEntity> byName = classService.findByName(classEntity.getName());
        if (byName.isPresent() && !byName.get().getId().equals(classEntity.getId())) {
            result.put("success", false);
            result.put("message", "班级名已存在");
            return result;
        }
        exist.get().setName(classEntity.getName());
        classService.save(exist.get());
        result.put("success", true);
        return result;
    }

    @PostMapping("/delete")
    public Map<String, Object> delete(@RequestBody Map<String, Long> param) {
        Map<String, Object> result = new HashMap<>();
        Long id = param.get("id");
        if (id == null || classService.findById(id).isEmpty()) {
            result.put("success", false);
            result.put("message", "班级不存在");
            return result;
        }
        classService.deleteById(id);
        result.put("success", true);
        return result;
    }

    /**
     * 获取班级详情
     */
    @GetMapping("/detail")
    public Map<String, Object> detail(@RequestParam Long id) {
        Map<String, Object> result = new HashMap<>();

        Optional<ClassEntity> classEntity = classService.findById(id);
        if (classEntity.isEmpty()) {
            result.put("success", false);
            result.put("message", "班级不存在");
            return result;
        }

        result.put("success", true);
        result.put("data", classEntity.get());

        return result;
    }
}
